// components/GoodsSku/GoodsSku.js
Component({
  properties: {
    basicInfo:{
      type:Object,
      default:null,
    },
    propList:{
      type:Array,
      default:[],
    }
  },

  data: {
    chooseProps:[],  //选择的商品属性数组: [1.5M, 胭脂粉]
    // 选择的是商品属性id
    choosePropsIds:[],   // ['propertyId:id', 'propertyId:id']
    count:1, //商品数量
  },
  lifetimes:{
    attached(){}
  },
  methods: {
    addshu(e){
      this.data.count = e.detail

    },
    //点击子集类目
    itemClick(e){
      //获取外层循环的index1和内层循环index2
      let {index1,index2,item1,item2} = e.currentTarget.dataset;
      //赋值
      this.properties.propList[index1].activeIndex= index2;
      // console.log( this.properties.propList[index1].activeIndex,' this.properties.propList[index1].activeIndex');
      //把商品属性添加到数据
      let name=  this.properties.propList[index1].childsCurGoods[index2].name   //获取属性名称
      this.data.chooseProps[index1]=name     //把属性名称添加到数组
     
      this.data.choosePropsIds[index1] = item1.id+ ":" +item2.id;
      // console.log(this.data.choosePropsIds);
     
      //渲染到页面
      this.setData({
        propList:this.properties.propList
      })   
      // console.log(this.properties.propList,'this.properties.propList'); 
    },
    addShow(){
      // 验证是否登录
      let token = wx.getStorageSync('token')
      if(!token){
        wx.reLaunch({
          url: '/pages/login/login',
        })
      }

      //判断是否选择属性
      if(this.data.chooseProps.length < this.properties.propList.length){
        wx.showToast({
          title:"请选择商品属性",
          icon:"error"
        })
        return
      }
      let cart = wx.getStorageSync("cart")  || [];
      // console.log(this.properties.basicInfo,'this.properties.basicInfo');
      let {id:goodsId,pic,name,minPrice} = this.properties.basicInfo
      let info={
        goodsId,  //商品id
        id:this.data.choosePropsIds.join(","),
        checked:false,
        pic,
        name,
        minPrice,
        count:this.data.count,
        props:this.data.chooseProps.join(" "),  //处理成字符串
        // propsId:this.data.choosePropsId.join(" ")  //处理成字符串
      }

      //判断商品在缓存中是否存在
      console.log();
      let index = cart.findIndex((item)=>{
        return item.id == info.id && item.props == info.props;
      })
      //不存在,直接添加
      if(index==-1){
        cart.unshift(info)
      }
      //存储到缓存
      wx.setStorageSync('cart', cart)
    }
  }
})
